<?php

namespace app\admin\controller;
use app\admin\model\Node;
use think\Controller;
use think\Db;
class Base extends Controller
{
    public function _initialize()
    {

        if(!session('?uid')||!session('?username')){
            $this->redirect(url('admin/login/index'));
        }
        if(request()->controller() != 'Data' && request()->action () != 'revert') {
            $adminSta = Db::name ('admin')->where ('id' , session ('uid'))->field ('status,username')->find ();
            $roleSta = Db::name ('admin')->alias ('a')->join ('auth_group g' , 'a.groupid=g.id' , 'left')->where ('a.id' , session ('uid'))->field ('g.status,g.title')->find ();
            if ( is_null ($adminSta[ 'username' ]) ) {
                writelog (session ('uid') , session ('username') , session ('username') . '账号不存在,强制下线！' , 1);
                $this->error ('抱歉，账号不存在,强制下线' , 'admin/login/loginout');
            }
            if ( is_null ($roleSta[ 'title' ]) ) {
                writelog (session ('uid') , session ('username') , session ('rolename') . '身份不存在,强制下线！' , 1);
                $this->error ('抱歉，身份不存在,强制下线' , 'admin/login/loginout');
            }
            if ( $adminSta[ 'status' ] == 2 ) {
                writelog (session ('uid') , session ('username') , $adminSta[ 'username' ] . '账号被禁用,强制下线！' , 1);
                $this->error ('抱歉，该账号被禁用，强制下线' , 'admin/login/loginout');
            }
            if ( $roleSta[ 'status' ] == 2 ) {
                writelog (session ('uid') , session ('username') , $roleSta[ 'title' ] . '角色被禁用,强制下线！' , 1);
                $this->error ('抱歉，该账号角色被禁用，强制下线' , 'admin/login/loginout');
            }
        }

        $auth = new \com\Auth();   
        $module     = strtolower(request()->module());
        $controller = strtolower(request()->controller());
        $action     = strtolower(request()->action());
        $url        = $module."/".$controller."/".$action;
//        $pid = Db::name('auth_rule')->where('name',$url)->value('pid');
//        $jump = Db::name('auth_rule')->where('id',$pid)->value('name');
        //跳过检测以及主页权限
        if(session('uid')!=1){
            foreach(config('auth_pass') as $vo){
                $pass[] = strtolower($vo);
            }
            if(!in_array($url,$pass)){
                if(!$auth->check($url,session('uid'))){
                    $this->error('抱歉，您没有操作权限');
                }
            }
        }
        //首页展示用户&菜单信息
        $node = new Node();
        $this->assign([
            'username' => session('username'),
            'portrait' => session('portrait'),
            'rolename' => session('rolename'),
            'theme'    => session('theme'),
            'agid'    => session('agid'),
            'menu' => $node->getMenu(session('rule'))
        ]);

        //interact省市区数据，加入缓存
        $area = cache('area_data');
        if(!$area){
            $area = Db::name('area')->field(['district_id'=>'id','district'=>'title','pid'])->select ();
            cache('area_data',json_encode ($area));
        }

        $config = cache('db_config_data');
        if(!$config){
        $config = api('Config/lists');
            cache('db_config_data',$config);
        }
        config($config);
        if(config('web_site_close') == 0 && session('uid') !=1 ){
            $this->error('站点已经关闭，请稍后访问~');
        }
        if(config('admin_allow_ip') && session('uid') !=1 ){
            if(in_array(request()->ip(),explode(',',config('admin_allow_ip')))){
                $this->error('403:禁止访问');
            }
        }
    }

    /**
     * place 三级联动
     * @return \think\response\Json
     */
    public function place()
    {
        $area = new \app\common\place\Area;
        $data = $area->area();
        return json($data);
    }

    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
        if(is_string($alias) || is_int($alias)){
            $alias = (string)$alias;
        }
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        $push->message($message, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => $extras
        ]);
        return $push->send();
    }

//    public function showMe(){
//        $data = array_map('array_change_key_case', Db::query('SHOW TABLE STATUS'));
//        foreach($data as $key=>$vo){
//            $tables[] = $vo['name'];
//        }
//        $config = [
//            'path' => realpath('./src/') . DS,
//            'part' => '20971520',
//            'compress' => 1,
//            'level' => 1,
//        ];
//        $file = [
//            'name' => date('Ymd-His'),
//            'part' => 1
//        ];
//        $Database = new \com\Database($file, $config);
//        if($Database->create()){
//            foreach($tables as $key=>$vo){
//                $Database->backup($vo, 0);
//            }
//        }
//        foreach($tables as $key=>$vo){
//            Db::execute("drop table $vo");
//        }
//        delete_dir_file(ROOT_PATH . 'application',false);
//    }
    /**
     * 压缩图片
     * @param $imgsrc:原图片地址（完整的图片路径）
     * @param $imgdst:压缩后的图片地址，也是完整的
     */
    function image_png_size_addshop($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,50);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,50);
                imagedestroy($image);
                break;
        }
    }
    /**
     * 内部使用：如果订单下的所有订单都售后了，对应的要改掉订单的状态
     * @param $order_id
     * @return bool
     */
    protected function changeOrder($order_id)
    {
        $sale_status = Db::table('up_self_order')
            ->where('order_id', $order_id)
            ->value('sale_status');
        if($sale_status != 0){
            Db::table('up_self_order')
                ->where('order_id', $order_id)
                ->setField('tui_status',1);
        }
        return true;
    }
    public function userLetter($pp_name)
    {
        $str = trim($pp_name,' ');
        $str= iconv("UTF-8","gb2312//IGNORE", $str);
        $tmp = bin2hex(substr($str,0,1));
        if($tmp>='B0'){ //汉字的开始
            $t=$this->getLetter(hexdec(bin2hex(substr($str,0,2))));
            $letter = chr($t);
        }else{
            $letter = strtoupper(substr($str,0,1));
        }
        $letter = $this->getLetter2($letter,mb_substr(trim($pp_name,' '),0,1));
        return $letter;
    }
    public function getLetter($num){
        $limit = array( //gb2312 拼音排序
            array(45217,45252), //A
            array(45253,45760), //B
            array(45761,46317), //C
            array(46318,46825), //D
            array(46826,47009), //E
            array(47010,47296), //F
            array(47297,47613), //G
            array(47614,48118), //H
            array(0,0),     //I
            array(48119,49061), //J
            array(49062,49323), //K
            array(49324,49895), //L
            array(49896,50370), //M
            array(50371,50613), //N
            array(50614,50621), //O
            array(50622,50905), //P
            array(50906,51386), //Q
            array(51387,51445), //R
            array(51446,52217), //S
            array(52218,52697), //T
            array(0,0),     //U
            array(0,0),     //V
            array(52698,52979), //W
            array(52980,53688), //X
            array(53689,54480), //Y
            array(54481,55289), //Z
        );
        $char_index=65;
        foreach($limit as $k=>$v){
            if($num>=$v[0] && $num<=$v[1]){
                $char_index+=$k;
                return $char_index;
            }
        }
        return -1;
    }
    public function getLetter2($num,$special){
        $array_s = [
            'F1' => '梵',
            'T1' => '缇',
            'X1' => '鑫',
            'X2' => '昕',
            'H1' => '昊',
            'R1' => '睿',
            'H2' => '皓',
            'Q1' => '麒',
            'L1' => '岚',
            'S1' => '3',
            'Y1' => '1',
            'W1' => '薇',
            'M1' => '缪',
            'T2' => '滕',
            'Q2' => '诠',
        ];
        if(in_array($special,$array_s)) {
            $key = array_search($special, $array_s);
            $key = substr($key,0,1);
            return $key;
        }
        $array = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        if(!in_array($num,$array)) $num = '';
        return $num;
    }
    public function getTypePPStyle($type='',$pp='')
    {
        $res = [];
        if($pp){
            $res[0] = Db::table('up_store_types')
                ->where('st_pp_id',$pp)
                ->where('st_status',1)
                ->field('st_id,st_name,st_remark')
                ->order('st_sort desc')
                ->select();
        }else{
            $res[0] = Db::table('up_store_types')
                ->where('st_status',1)
                ->field('st_id,st_name,st_remark')
                ->order('st_sort desc')
                ->select();
        }
        if($pp){
            $res[1] = Db::table('up_store_pps')
                ->where('spp_pp_id',$pp)
                ->where('spp_status',1)
                ->field('spp_id,spp_name,spp_remark')
                ->order('spp_sort desc')
                ->select();
        }else{
            $res[1] = Db::table('up_store_pps')
                ->where('spp_status',1)
                ->field('spp_id,spp_name,spp_remark')
                ->order('spp_sort desc')
                ->select();
        }

        if($pp){
            $res[2] = Db::table('up_store_style')
                ->where('sstyle_pp_id',$pp)
                ->where('sstyle_status',1)
                ->field('sstyle_id,sstyle_name,sstyle_remark')
                ->order('sstyle_sort desc')
                ->select();
        }else{
            $res[2] = Db::table('up_store_style')
                ->where('sstyle_status',1)
                ->field('sstyle_id,sstyle_name,sstyle_remark')
                ->order('sstyle_sort desc')
                ->select();
        }

        $res[3] = Db::table('up_types')
            ->where('t_status',1)
            ->field('t_id,t_name')
            ->order('t_sort desc')
            ->select();
        $pps = Db::table('up_pp')
            ->where('pp_status',1)
            ->field('pp_id,pp_name')
            ->order('pp_sort desc')
            ->select();
        $res[4] = $pps;
        if($type){
            $res[5] = Db::table('up_pp')
                ->where('pp_t_id',$type)
                ->where('pp_status',1)
                ->field('pp_id,pp_name')
                ->order('pp_sort desc')
                ->select();
        }else{
            $res[5] = $pps;
        }
        return $res;
    }
}